package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.PO.ProductTypePO;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.constants.RabbitMQConstant;
//import com.itlong.cloud.iot.service.server.impl.AliIotServerServiceImpl;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 *  云电梯产品型号信息同步至IOT的队列消费者  (最新iot版本此方法暂时摒弃)
 * @createDate 2018-03-14
 */
//@Component
public class ProductIotConsumer {
    private static final Logger LOG = LoggerFactory.getLogger(ProductIotConsumer.class);

//    @Autowired
//    AliIotServiceImpl aliIotServiceImpl;


    /**
     * <desc>
     *     云电梯产品型号信息同步至IOT消费端
     * </desc>
     * @param message
     * @param channel
     * @throws InterruptedException
     * @throws IOException
     */
//    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_PRODUCT_QUEUE)
    public void process(Message message, Channel channel) throws InterruptedException, IOException {
        byte[] body = message.getBody();
        LOG.info("RabbitMQ_云电梯产品型号信息同步至IOT消费端:"+body);
        try {
            TimeTaskDeadMessageQueuePO timeTaskDeadMessageQueuePO = JSON.parseObject(new String(body), TimeTaskDeadMessageQueuePO.class);
            JSONObject dataJs = JSON.parseObject(timeTaskDeadMessageQueuePO.getMessageContent());
            String dajs = dataJs.getString("data");
            ProductTypePO productTypePO = JSONObject.parseObject(dajs,ProductTypePO.class);
            boolean flag = false;
            if (StringUtils.isNotBlank(productTypePO.getIotProductKey())){
//                flag = aliIotServiceImpl.updateProduct(productTypePO);
            }else {
//                flag = aliIotServiceImpl.createProduct(productTypePO);
            }
            if (flag){
                LOG.info("【RabbitMQ_云电梯产品型号信息同步至IOT消费端】消费成功");
            }else {
                LOG.info("【RabbitMQ_云电梯产品型号信息同步至IOT消费端】消费失败");
            }
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            LOG.error("【RabbitMQ_云电梯产品型号信息同步至IOT消费端】:解析异常",e);
        } finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }




}
